'''
This module contains a code editor based on QScintilla.
'''

import os
from PyQt4 import QtGui
from SimpleCells.Components.Shell.SCShell import getCodeFont

# Trying to import QsciScintilla
try:
    from PyQt4.Qsci import QsciScintilla, QsciLexerPython
    class SCPythonLexer(QsciLexerPython):
        def __init__(self,parent=None):
            QsciLexerPython.__init__(self,parent)
            self.setDefaultFont(getCodeFont())
            self.setFont(getCodeFont(italic=True),self.Comment)
            self.commentString = '#'
            self.blockCommentStrings = None
    
    class SCCodeEditor(QsciScintilla):
        '''
        A class for showing and editing Python codes.
        '''
        def __init__(self,parent=None):
            QsciScintilla.__init__(self,parent)
            
            # user interface setup
            self.setAutoIndent(True)
            self.setIndentationWidth(4)
            self.setAutoCompletionThreshold(4)
            self.setAutoCompletionSource(QsciScintilla.AcsDocument)
            self.setFolding(QsciScintilla.BoxedFoldStyle)
            self.setMarginWidth(1,40)
            self.setMarginLineNumbers(1,True)
            self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
            
            # Font
            font = getCodeFont()
            self.setFont(font)
    
            # Lexer
            lexer = SCPythonLexer(self)
            self.setLexer(lexer)
    
        #def keyPressEvent(self, ev):
        #    """
        #    Re-implemented to handle the user input a key at a time.
        #    
        #    @param ev key event (QKeyEvent)
        #    """
        #    txt = ev.text()
        #    key = ev.key()
        #    
        #    ctrl = ev.modifiers() & Qt.ControlModifier
        #    shift = ev.modifiers() & Qt.ShiftModifier
        #    # See it is text to insert.
        #    if(self.keymap.has_key(key) and not shift and not ctrl):
        #        self.keymap[key]()
        #
        #    elif self.__isCursorOnLastLine() and txt.length() :
        #
        #        QsciScintilla.keyPressEvent(self, ev)
        #        self.incrementalSearchActive = True
        #        
        #        if(txt == '.'):
        #            self.__showDynCompletion()
        #
        #    elif(ctrl or shift):
        #        QsciScintilla.keyPressEvent(self, ev)
        #
        #
        #    else:
        #        ev.ignore()
    
        def comment(self):
            '''comment out the selected text or current line'''
            lex = self.lexer()
            if not lex:
                return
    
            commentStr = lex.commentString
            selection = self.getSelection()
            self.beginUndoAction()
            if not self.hasSelectedText():
                line, index = self.getCursorPosition()
                lines_to_comment = [line,]
            else:
                lineFrom, indexFrom, lineTo, indexTo = self.getSelection()
    
                if indexTo == 0:
                    endLine = lineTo - 1
                else:
                    endLine = lineTo
    
                lines_to_comment = range(lineFrom, lineTo+1)
    
            newsel = list(selection)
            if commentStr:
                for line in lines_to_comment:
                    self.insertAt(commentStr, line, 0)
    
                newsel[1] += len(commentStr)
                newsel[3] += len(commentStr)
    
            self.setSelection(*newsel)
            self.endUndoAction()
    
        def uncomment(self):
            '''uncomment selected lines'''
            lex = self.lexer()
            if not lex:
                return
    
            commentStr = lex.commentString
            bCommentStr = lex.blockCommentStrings
    
            lines_to_uncomment = []
            selection = self.getSelection()
            self.beginUndoAction()
            if not self.hasSelectedText():
                line, index = self.getCursorPosition()
                lines_to_uncomment.append(line)
            else:
                lineFrom, indexFrom, lineTo, indexTo = self.getSelection()
                if indexTo == 0:
                    endLine = lineTo - 1
                else:
                    endLine = lineTo
    
                lines_to_uncomment = range(lineFrom, lineTo+1)
    
            newsel = list(selection)
            if commentStr:
                for line in lines_to_uncomment:
                    self.setSelection(line, 0, line, len(commentStr))
                    if self.selectedText().toUtf8() == commentStr:
                        self.removeSelectedText()
    
                newsel[1] -= len(commentStr)
                newsel[3] -= len(commentStr)
    
            self.setSelection(*newsel)
            self.endUndoAction()
except ImportError:
    print 'QScintilla must be installed in order to correctly use SimpleCells.'
    from PyQt4.QtGui import QTextEdit
    class SCCodeEditor(QTextEdit):
        def __init__(self,parent=None):
            QTextEdit.__init__(self,parent)


if __name__ == '__main__':
    pass
